<?php

namespace app\common\model;

use app\helpers\Common;
use app\libs\traits\BaseModelTrait;

use think\model\concern\SoftDelete;

class AdminRole extends Base
{
    /**
     * Base Model Trait
     */
    use BaseModelTrait;

    //use SoftDelete;

    protected $deleteTime = 'deleted_at';

    // 当前模型名称 不带前缀
    protected $name = 'admin_roles';

    // 主键
    protected $pk = 'id';

    // 字段验证规则
    protected $validate = true;

    // 定义全局的查询范围
    protected $globalScope = ['status'];

    public function scopeStatus($query)
    {
        $query->where('status', '<>', config('constants.SOFT_DELETE_STATUS'));
    }

    /**
     * Set sorting attribute
     *
     * @param $value
     * @return int
     */
    public function setSortingAttr($value)
    {
        return !empty($value) ? $value : 0;
    }

    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {
        foreach ($list as &$item) {
            $item = self::formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $params = '')
    {
        if (!$item) {
            return '';
        }

        $item['access_ids'] = explode(',', $item['access']);

        return $item;
    }

    /**
     * 是否被使用过
     */
    public function isUsed($id, $param = '')
    {
        if (!$id) {
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 是否有管理员
        $roleUserWhere = [
            ['role_id', '=', $id]
        ];
        $roleUser = \app\common\model\AdminRoleUser::where($roleUserWhere)->field('id')->find();
        if ($roleUser) {
            return ['code' => 0, 'msg' => '该角色下有管理员，请先删除管理员'];
        }

        return ['code' => 1, 'msg' => ''];
    }
}
